package com.ge.med.cchelper.popup.job;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.ge.med.cchelper.bean.Response;
import com.ge.med.cchelper.util.LogUtil;
import com.ge.med.cchelper.util.SSLhelper;
import com.ge.med.cchelper.util.ftp.FTPFactory;
import com.ge.med.cchelper.util.ftp.FtpHelper;

public class SyncFileJob extends BaseJob{

	private IFile selectedIFile;

	public SyncFileJob(String message,IFile selectedIFile) {
		super(message);
		this.selectedIFile = selectedIFile;	
	}

	
	protected IStatus start(IProgressMonitor arg0) {

		String noUse = selectedIFile.getFullPath().segment(1);
		String allPath = selectedIFile.getFullPath().toString();
		String realTempPath = allPath.substring(allPath
				.indexOf(noUse) + noUse.length());
		String fileName = selectedIFile.getFullPath()
				.lastSegment();

		String fullPath = selectedIFile.getLocation()
				.toOSString();
		String vobsPath = csession.getVobRoot();
		String remotePath = vobsPath + realTempPath;

		LogUtil.out("Synchronize " + fileName + " from host...");

		SSLhelper sslHelper = new SSLhelper(csession);
		Response res = sslHelper.executeCT("cp -rf " + remotePath
				+ " " + sourceTempDir);
		int flag = res.getStatus();
		if (flag == 0) {
			FtpHelper ftp = null;

			try {
				ftp = FTPFactory.getConnectionInstance(csession.getHost(), ".");
				if (ftp.downloadPlus(
						sourceTempDir + "/" + fileName,
						fullPath,arg0,false)) {
					sslHelper.execute("rm -rf " + sourceTempDir
							+ "/" + fileName);
				}
			} catch (Exception e) {
				LogUtil.err("Ftp failed." + e.getMessage());
				e.printStackTrace();
				return Status.CANCEL_STATUS;
			}
		} else {
			return Status.CANCEL_STATUS;
		}

		LogUtil.out("Synchronize completed.");
		try {
			selectedIFile.refreshLocal(IResource.DEPTH_ONE, null);
		} catch (CoreException e) {
			e.printStackTrace();
			LogUtil.err("refresh failed."
					+ e.getMessage());
		}
		return Status.OK_STATUS;
	
	}

}
